package com.ruoyi.system.service.impl;

import java.io.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.StockBase;
import com.ruoyi.system.domain.StockLt;
import com.ruoyi.system.domain.vo.StockDayVO;
import com.ruoyi.system.mapper.StockBaseMapper;
import com.ruoyi.system.mapper.StockLtFootmanMapper;
import com.ruoyi.system.mapper.StockLtMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.StockDayMapper;
import com.ruoyi.system.domain.StockDay;
import com.ruoyi.system.service.IStockDayService;

import javax.annotation.PostConstruct;

/**
 * 每日记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@Service
public class StockDayServiceImpl implements IStockDayService 
{
    private static final Logger log = LoggerFactory.getLogger(StockDayServiceImpl.class);

    @Autowired
    private StockDayMapper stockDayMapper;

    @Autowired
    private StockBaseMapper stockBaseMapper;

    @Autowired
    private StockLtMapper stockLtMapper;

    @Autowired
    private StockLtFootmanMapper stockLtFootmanMapper;

    @Autowired
    private StockBaseServiceImpl stockBaseService;

    @PostConstruct
    public void init()
    {
        loadingPlateCache();
    }

    /**
     * 加载个股代码缓存
     */
    private void loadingPlateCache() {
/*        List<SysBaseShare> shares = sysBaseShareMapper.selectSysBaseShareList(new SysBaseShare());
        Map<Object, String> shareCodeCache = shares.stream().collect(Collectors.toMap(SysBaseShare::getShareCode, SysBaseShare::getShareName));
        Map<Object, String> shareNameCache = shares.stream().collect(Collectors.toMap(SysBaseShare::getShareName, SysBaseShare::getShareCode));

        ShareUtils.setShareCache(ShareConstants.SHARE_CODE,shareCodeCache);
        ShareUtils.setShareCache(ShareConstants.SHARE_NAME,shareNameCache);*/
    }

    /**
     * 查询每日记录
     * 
     * @param recordId 每日记录主键
     * @return 每日记录
     */
    @Override
    public StockDay selectStockDayByRecordId(Long recordId)
    {
        return stockDayMapper.selectStockDayByRecordId(recordId);
    }

    /**
     * 查询每日记录列表
     * 
     * @param stockDay 每日记录
     * @return 每日记录
     */
    @Override
    public List<StockDay> selectStockDayList(StockDay stockDay)
    {
        return stockDayMapper.selectStockDayList(stockDay);
    }

    /**
     * 新增每日记录
     * 
     * @param stockDay 每日记录
     * @return 结果
     */
    @Override
    public int insertStockDay(StockDay stockDay)
    {
        return stockDayMapper.insertStockDay(stockDay);
    }

    /**
     * 修改每日记录
     * 
     * @param stockDay 每日记录
     * @return 结果
     */
    @Override
    public int updateStockDay(StockDay stockDay)
    {
        return stockDayMapper.updateStockDay(stockDay);
    }

    /**
     * 批量删除每日记录
     * 
     * @param recordIds 需要删除的每日记录主键
     * @return 结果
     */
    @Override
    public int deleteStockDayByRecordIds(Long[] recordIds)
    {
        return stockDayMapper.deleteStockDayByRecordIds(recordIds);
    }

    /**
     * 删除每日记录信息
     * 
     * @param recordId 每日记录主键
     * @return 结果
     */
    @Override
    public int deleteStockDayByRecordId(Long recordId)
    {
        return stockDayMapper.deleteStockDayByRecordId(recordId);
    }

    /**
     * 每日板块数据导入 待完善
     * @param stockList
     * @param updateSupport
     * @param date
     * @return
     */
    @Override
    public String importUser(List<StockDayVO> stockList, boolean updateSupport, String date) {
        date = StringUtils.isNotEmpty(date)?date:DateUtils.dateTime();
        if (StringUtils.isNull(stockList) || stockList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (StockDayVO stock : stockList)
        {
            if (Objects.isNull(stock.getClosePrice())){
                continue;
            }
            try
            {
                StockDay bean = BeanUtil.toBean(stock, StockDay.class);
                //主键处理
                String id = stock.getStockCode().substring(2, 8);
                bean.setRecordId(Long.valueOf(date+id));
                //时间处理
                if (Objects.nonNull(stock.getLimitBeginTime())){
                    bean.setLimitBeginTime(DateUtil.parseDateTime(DateUtil.formatDate(new Date())+" "+DateUtil.formatTime(stock.getLimitBeginTime())));
                }
                if (Objects.nonNull(stock.getLimitEndTime())){
                    bean.setLimitEndTime(DateUtil.parseDateTime(DateUtil.formatDate(new Date())+" "+DateUtil.formatTime(stock.getLimitEndTime())));
                }
                //处理封单额和封成比
                bean.setLimitSeal(compute(stock.getLimitSeal()));
                bean.setLimitRatio(compute(stock.getLimitRatio()));

                if (Objects.nonNull(stock.getRate())){
                    bean.setRate(NumberUtil.round(stock.getRate() * 100  ,2));
                }
                if (Objects.nonNull(stock.getChangeRatio())) {
                    bean.setChangeRatio(NumberUtil.round(stock.getChangeRatio() * 100, 2));
                }
                // 验证缓村中是否存在
                //Boolean plateCache = StockUtils.getShareCache(ShareConstants.PLATE, plate.getPlateName(), plate.getPlateName());
                this.insertStockDay(bean);
                successNum++;
                successMsg.append("<br/>" + successNum + "、物票 " + stock.getStockName() + " 导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、物票: " + stock.getStockName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public String screen(String path) {
        DateTime beginDate = DateUtil.parse("2023/07/31", "yyyy/MM/dd");
        long between = DateUtil.between(beginDate, new Date(), DateUnit.DAY);
        for (long i = 0; i < between; i++) {
            String date = DateUtil.formatDate(DateUtil.offsetDay(beginDate, (int) i));
            //获取今天的最大值,然后查询下有几条数据,如果是一条判断下是否和前天一样,一样就天数加一天,
            // 不一样就把当天的分类数据那出来
            List<StockBase> maxList = stockBaseMapper.todayMax(date);
            if (maxList.size()==1){
                StockBase stockBase = maxList.get(0);
                StockLt lastLt = stockLtMapper.lastInfo();
                if (stockBase.getStockCode().equals(lastLt.getStockCode())){
                    //数据相同天数加一天
                    lastLt.setLimitDays(lastLt.getLimitDays()+1L);
                    stockLtMapper.updateStockLt(lastLt);
                }else {
                    //数据不同则开始捞数据,把相关的数据全部入
                    //断板当日首版
                    //断板当日一进二
                    //断板次日首板
                    //龙头首版同日
                }
            }
        }

        return null;
    }

    @Override
    public String readFile(String path) {

        DateTime beginDate = DateUtil.parse("2023/07/31", "yyyy/MM/dd");
        File directory = new File(path);
        File[] files = directory.listFiles();
        for (File file : files) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(new FileInputStream(file.getPath()), "GB2312"));
                String line;
                boolean begin = false;
                StockBase base = getBase(reader.readLine());
                reader.readLine();
                while ((line = reader.readLine()) != null) {
                    String[] info = line.split("\t");
                    if (info.length<2){
                        continue;
                    }
                    if (!begin){
                        DateTime parse = DateUtil.parse(info[0], "yyyy/MM/dd");
                        begin = parse.getTime() > beginDate.getTime();
                    }else {
                        BigDecimal yesterday = Optional.ofNullable(base.getClosePrice()).orElse(new BigDecimal(0));
                        base.setRecordId(Long.valueOf(info[0].replace("/","")+base.getStockCode()));
                        base.setOpenPrice(new BigDecimal(info[1]));
                        base.setHIGH(new BigDecimal(info[2]));
                        base.setLOW(new BigDecimal(info[3]));
                        base.setClosePrice(new BigDecimal(info[4]));
                        base.setTURNOVER(new BigDecimal(info[5]));
                        base.setTurnVolume(new BigDecimal(info[6]));
                        base.setCrteTime(DateUtil.parse(info[0], "yyyy/MM/dd"));
                        BigDecimal increase = base.getClosePrice().subtract(yesterday).divide(base.getClosePrice(), 2);
                        if (base.getClosePrice().compareTo(base.getHIGH())==0 && base.getClosePrice().compareTo(base.getOpenPrice())!=-1 && increase.compareTo(new BigDecimal(0.08))>0){
                            base.setLimitDays(Optional.ofNullable(base.getLimitDays()).orElse(0L)+1L);
                        }else {
                            base.setLimitDays(0L);
                        }
                        stockBaseService.insertStockBase(base);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    private StockBase getBase(String name) throws IOException {
        String[] baseInfo = name.split(" ");
        Long recordId = Long.valueOf("20230801"+baseInfo[0]);
        StockBase stockBase = stockBaseService.selectStockBaseByRecordId(recordId);
        if (Objects.isNull(stockBase)){
            stockBase = new StockBase();
            stockBase.setRecordId(recordId);
            stockBase.setStockCode(baseInfo[0]);
            stockBase.setStockName(baseInfo[1]);
        }
        return stockBase;
    }


    private Double compute(String value) {
        if (StringUtils.isNotEmpty(value)){
            Double multiplicand = 1.0;
            if (value.contains("万")){
                value = value.replace("万", "");
                multiplicand = 10000.0;
            }

            if (value.contains("亿")){
                value = value.replace("亿", "");
                multiplicand = 100000000.0;
            }
            return Double.valueOf(value) * multiplicand;
        }
        return null;
    }
}
